﻿using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Text;
using WorkFlowCore.IRepositories;

namespace WorkFlowCore.Framework.Repositories4EF
{
    public class UnitOfWork4EF : IUnitOfWork
    {

        private bool isActive = false;
        private readonly WorkflowDbContext workflowDbContext;
        private IDbContextTransaction dbContextTransaction=null;
        private int beginLevel = 0;

        public UnitOfWork4EF(WorkflowDbContext workflowDbContext)
        {
            this.workflowDbContext = workflowDbContext;
        }


        public bool Commit()
        {
            beginLevel--;
            //如果开启了多层事务，则最外层才提交 
            if (beginLevel > 0)
            {

                return true;
            }

            isActive = false;
            try
            {
                workflowDbContext.SaveChanges();
                dbContextTransaction.Commit();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                //回滚
                dbContextTransaction.Rollback();
                return false;
            }
            
        }

        public void Dispose()
        {
            if(!isActive)
                dbContextTransaction?.Dispose();
        }

        public bool IsActive()
        {
            return isActive;
        }

        internal void Begin()
        {
            beginLevel++;
            //if (this.isActive) return;
            //this.dbContextTransaction = workflowDbContext.Database.BeginTransaction();
            //isActive = true;
        }
        internal void BeginWithoutLevel()
        {
            if (this.isActive) return;
            this.dbContextTransaction = workflowDbContext.Database.BeginTransaction();
            isActive = true;
        }
    }
}
